package com.sbs.gaoxinqutoilet.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.TextView;

import com.sbs.gaoxinqutoilet.R;
import com.sbs.gaoxinqutoilet.base.BaseScanActivity;
import com.sbs.gaoxinqutoilet.entity.UserEntity;
import com.sbs.gaoxinqutoilet.http.HttpApis;
import com.sbs.gaoxinqutoilet.http.Request;
import com.sbs.gaoxinqutoilet.interfaces.Constant;
import com.sbs.gaoxinqutoilet.interfaces.Constants;
import com.sbs.gaoxinqutoilet.myapp.MyApplication;
import com.sbs.gaoxinqutoilet.utils.GsonTools;
import com.sbs.gaoxinqutoilet.utils.HttpUtils;
import com.sbs.gaoxinqutoilet.utils.LogUtils;
import com.sbs.gaoxinqutoilet.utils.SPUtil;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by 聪明一只哈 on 2018/5/30.
 * Time: 2018/5/30  11:08
 */

public class LoginActivity extends BaseScanActivity {

    protected String[] needPermissions = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE
    };

    private static final int PERMISSON_REQUESTCODE = 0;

    private boolean isNeedCheck = true;

    @BindView(R.id.tv_title_show)
    TextView tvTitleShow;
    @BindView(R.id.tv_login_name)
    TextView tvLoginName;
    @BindView(R.id.tv_login_pass)
    TextView tvLoginPass;
    @BindView(R.id.bt_login)
    Button btLogin;
    private LoginRequest loginRequest;
    private String login_name;
    private String login_pass;


    @Override
    protected void initContentView(Bundle savedInstanceState) {
        //getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); //隐藏状态栏

        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);

    }

    @Override
    protected void initView() {

        if("http://219.148.34.40:8081".equals(HttpApis.IP)){
            tvTitleShow.setText("厕所革命测试");
        }

        String login_name = SPUtil.getString(Constants.LOGINNAME, "");
        if (!TextUtils.isEmpty(login_name)){
            tvLoginName.setText(login_name);
        }
        String login_pass = SPUtil.getString(Constants.LOGINPASS, "");
        if (!TextUtils.isEmpty(login_pass)){
            tvLoginPass.setText(login_pass);
        }



    }

    @Override
    protected void initLogic() {

    }

    @Override
    protected void getBundleExtras(Bundle extras) {

    }

    /**
     * 点击登录
     */
    @OnClick(R.id.bt_login)
    public void onViewClicked() {



        login_name = tvLoginName.getText().toString().trim();
        login_pass = tvLoginPass.getText().toString().trim();

        if (TextUtils.isEmpty(login_name)){
            showShortToast("手机号有误，请重新输入");
            return;
        }
        if (TextUtils.isEmpty(login_pass)){
            showShortToast("密码有误，请重新输入");
            return;
        }

        //手机号正则校验
//        if (!RegexUtils.isMobileExact(login_name)){
//            showShortToast("手机号格式不正确");
//            return;
//        }

        showLoadingDialog("正在登录...");

        SPUtil.putString(Constants.LOGINNAME,login_name);
        SPUtil.putString(Constants.LOGINPASS,login_pass);
        String mBuyUrl = HttpApis.login;

        HashMap<String ,String> map=new HashMap<>();
        map.put("name", login_name);
        map.put("password", login_pass);
        if (loginRequest==null){
            loginRequest = new LoginRequest();
        }
        HttpUtils.requestPost(this, mBuyUrl, map, loginRequest);


    }


    /**
     * 登录请求数据
     */
    private class LoginRequest extends Request {
        @Override
        public void success(String jsonStr) {
            super.success(jsonStr);
            LogUtils.i("loginAccount", "success: "+jsonStr);

            UserEntity loginEntity = GsonTools.changeGsonToBean(jsonStr, UserEntity.class);
            //数据解析
            processData(loginEntity);
            cancelLoadingDialog();
        }

        @Override
        public void error(String error) {
            super.error(error);
            LogUtils.i("loginAccount", "error: "+error);
            if(error.contains("503")){
                showAlertOnlyPos(LoginActivity.this,"未退出登录","用户已登录,请在设置页面退出再登录");
            }else{
                showShortToast("用户名或密码错误 ");
            }
            cancelLoadingDialog();

        }
    }

    /**
     * 数据解析
     * @param userEntity
     */
    private void processData(UserEntity userEntity) {
        if (userEntity != null) {
            saveInfor(userEntity);

            UserEntity userEntity1 = MyApplication.getUserEntity();
            if (userEntity1!=null){
                //没有状态码,先用假条件登录
                if (!"".equals(userEntity.getOpt_id())){
                    startActivity(new Intent(LoginActivity.this,MainActivity.class));
                    finish();
                }else {
                    showShortToast("用户名或密码有误，请重新输入");
                }
            }else {
                showShortToast("用户名或密码有误，请重新输入");
            }


        }
    }

    /**
     * 保存个人信息 存到application中,方便获取
     * @param userEntity
     */
    private void saveInfor(UserEntity userEntity) {
        //姓名
        SPUtil.putString(Constants.KEY_USERNAME, login_name);
        //不保存登录密码
        SPUtil.putString(Constant.KEY_USERPWD, login_pass);
        //login  token  每次请求都要带有这个token
        SPUtil.putString(Constants.KEY_TOKEN, userEntity.getToken());
        LogUtils.i("show_token_data",userEntity.getToken());
        MyApplication.setUserEntity(userEntity);
        SPUtil.putBeanValue(Constants.KEY_USER, userEntity);

    }


    @Override
    protected void onResume() {
        super.onResume();
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            if (isNeedCheck) {
                checkPermissions(needPermissions);
            }
        }
    }

    private void checkPermissions(String... permissions) {
        try {
            if (Build.VERSION.SDK_INT >= 23
                    && getApplicationInfo().targetSdkVersion >= 23) {
                List<String> needRequestPermissonList = findDeniedPermissions(permissions);
                if (null != needRequestPermissonList
                        && needRequestPermissonList.size() > 0) {
                    String[] array = needRequestPermissonList.toArray(new String[needRequestPermissonList.size()]);
                    Method method = getClass().getMethod("requestPermissions", new Class[]{String[].class,
                            int.class});

                    method.invoke(this, array, PERMISSON_REQUESTCODE);
                }
            }
        } catch (Throwable e) {
        }
    }

    private List<String> findDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissonList = new ArrayList<String>();
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23){
            try {
                for (String perm : permissions) {
                    Method checkSelfMethod = getClass().getMethod("checkSelfPermission", String.class);
                    Method shouldShowRequestPermissionRationaleMethod = getClass().getMethod("shouldShowRequestPermissionRationale",
                            String.class);
                    if ((Integer)checkSelfMethod.invoke(this, perm) != PackageManager.PERMISSION_GRANTED
                            || (Boolean)shouldShowRequestPermissionRationaleMethod.invoke(this, perm)) {
                        needRequestPermissonList.add(perm);
                    }
                }
            } catch (Throwable e) {

            }
        }
        return needRequestPermissonList;
    }

    @TargetApi(23)
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] paramArrayOfInt) {
        if (requestCode == PERMISSON_REQUESTCODE) {
            if (!verifyPermissions(paramArrayOfInt)) {
                showMissingPermissionDialog();
                isNeedCheck = false;
            }
        }
    }

    private boolean verifyPermissions(int[] grantResults) {
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 显示提示信息
     *
     * @since 2.5.0
     *
     */
    private void showMissingPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.notifyTitle);
        builder.setMessage(R.string.notifyMsg);

        // 拒绝, 退出应用
        builder.setNegativeButton(R.string.cancel,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });

        builder.setPositiveButton(R.string.setting,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startAppSettings();
                    }
                });

        builder.setCancelable(false);

        builder.show();
    }

    /**
     *  启动应用的设置
     *
     * @since 2.5.0
     *
     */
    private void startAppSettings() {
        Intent intent = new Intent(
                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }


}
